package com.wr.config;

import com.wr.constant.GlobalConstant;
import org.apache.log4j.Logger;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.amqp.rabbit.support.CorrelationData;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import javax.annotation.PostConstruct;
import java.util.UUID;

/**
 * @author weirong
 * @Title:
 * @Description:
 * @date 2018/6/1513:42
 */
@Component
public class Sender implements RabbitTemplate.ConfirmCallback, RabbitTemplate.ReturnCallback {

    Logger logger = Logger.getLogger(this.getClass());

    @Autowired
    RabbitTemplate rabbitTemplate;

    @PostConstruct
    public void inti() {
        rabbitTemplate.setConfirmCallback(this);
        rabbitTemplate.setReturnCallback(this);

    }
    @Override
    public void confirm(CorrelationData correlationData, boolean b, String s) {
        if(b) {
            logger.info("消息发送成功："+correlationData);
        }else {
            logger.info("消息发送失败："+s);
        }

    }

    @Override
    public void returnedMessage(Message message, int i, String s, String s1, String s2) {
        logger.info(message.getMessageProperties().getCorrelationIdString() + " 发送失败");

    }
    /**
     *    发送消息，不需要实现任何接口，供外部调用。
     */
    public void send(Object msg){

        CorrelationData correlationId = new CorrelationData(UUID.randomUUID().toString());

        logger.info("开始发送消息 : " + msg);
        String response = rabbitTemplate.convertSendAndReceive(GlobalConstant.TOPIC_EXCHANGE, GlobalConstant.BLOG_VIEW_COUNT_QUEUE, msg, correlationId).toString();
        logger.info("结束发送消息 : " + msg);
        logger.info("消费者响应 : " + response + " 消息处理完成");
    }
}
